
#import "EmpController.h"
#import <eointerface/eointerface.h>
#import "ValueForKey.h"
#import "SelectionInsertionAssociation.h"

@implementation EmpController

- appDidInit:sender
{
    // add custom association that inserts and deletes objects in the
    // empProjectsController based on the selection in the allProjectsController
    [empProjectsController addAssociation:[[SelectionInsertionAssociation alloc] initWithController:empProjectsController key:nil destination:allProjectsController]];

    // add custom association that inserts and deletes objects in the
    // empDeptsController based on the selection in the allDeptsController
    [empDeptsController addAssociation:[[SelectionInsertionAssociation alloc] initWithController:empDeptsController key:nil destination:allDeptsController]];

    // Fetch the list of all projects and all departments for our pick lists.
    // A real app would probably cache these list so it wouldn't have to
    // requery the database each time a new window is opened.
    [allProjectsController fetch:nil];
    [allDeptsController fetch:nil];

    // Set a controller in memory sort for first name and last name
    // and fetch all of the employees
    [empController setSortOrdering:[NSArray arrayWithObjects:
        [EOKeySortOrdering keyOrderingWithKey:@"last_name" ordering:NSOrderedAscending],
        [EOKeySortOrdering keyOrderingWithKey:@"first_name" ordering:NSOrderedAscending], nil]];
    [empController fetch:nil];

    return self;
}

- insert:sender
{
    // Add a new employee
    // In addition to inserting the employee itself, we need to insert
    // in any detail controller that represent mandatory to-one relationships.
    // Possible Enhansement: make the Savvy controller propagate inserts to
    // detail controllers automatically.
    [empController insert:self];
    [quoteController insert:self];
    [photoController insert:self];
    // default the department for the new employee to the first department in the list 
    [empDeptsController insertObject:[[allDeptsController allObjects] objectAtIndex:0] atIndex:0];
    return self;
}

- (BOOL)controllerWillDiscardOperations:(EOController *)controller
{
    // Application policy: if they fetch or change selection,
    // automatically save the current employee data.
    return [self save:nil] ? YES : NO;
}


- save:sender
{
    [empController saveToDataSource];

    // Updates to controllers (like our department) may have changed property
    // values that we display in the master.
    // Re-sort in case the save changed the sort attributes
    [empController resort];

    return self;
}

@end
